package com.etocrm.saas.lib.base.server.converter;

import com.etocrm.saas.lib.base.common.enums.base.BaseEnum;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;

import java.util.HashMap;
import java.util.Map;

public class StringToEnumConverterFactory implements ConverterFactory<String, BaseEnum> {

    private static final Map<Class, Converter> converterMap = new HashMap<>();

    @Override
    public <T extends BaseEnum> Converter<String, T> getConverter(Class<T> targetType) {
        return converterMap.computeIfAbsent(targetType, aClass -> new StringToEnumConverter<>(targetType));
    }

    static class StringToEnumConverter<T extends BaseEnum> implements Converter<String, T> {
        private final Map<String, T> enumMap = new HashMap<>();

        StringToEnumConverter(Class<T> enumType) {
            T[] enums = enumType.getEnumConstants();
            for (T e : enums) {
                enumMap.put(String.valueOf(e.getValue()), e);
            }
        }

        @Override
        public T convert(String source) {
            return enumMap.get(source);
        }
    }

}
